import axios from 'axios';
import qs from 'qs';
if(window.location.hostname!='localhost'){
  axios.defaults.baseURL='http://yh.qikwl.com/';
}else{
  axios.defaults.baseURL='/api';
}
axios.defaults.timeout=5000;
import store from '@/vuex/index';
import router from '@/libs/router';
let loadingNum=0;
let loadingTimeOut = null;
import { Indicator } from 'mint-ui';
let  loading = true;

axios.interceptors.request.use(config => {
  //console.log(Vue.loading)
	if (config.url.indexOf("lastplay") > -1)
	{
		//loadingNum++;
		return config;
	}
  if(loading){
    Indicator.open({
      text: '加载中...',
      spinnerType: 'fading-circle'
    });
  }

  loadingNum++;
  return config
});
axios.interceptors.response.use(function (res){
  let key=res.headers.authorization;
  if (key){
    localStorage.setItem('token',key);
  }
  return res;
},function(error){
  // Do something with res error
  return Promise.reject(error);
});
const fetch = (opts,data) => {
  let httpDefaultOpts={ //http默认配置
    method:opts.method,
    url:opts.url,
    timeout:10000,
    params:data,
    data:qs.stringify(data),
    headers:opts.method == 'get' ? {
      'X-Requested-With': 'XMLHttpRequest',
      "Accept": "application/json",
      "Content-Type": "application/json; charset=UTF-8"
    } : {
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
  };


  if (opts.method == 'get') {
    delete httpDefaultOpts.data
  } else {
    delete httpDefaultOpts.params
  }


  let promise = new Promise(function (resolve, reject) {
    axios(httpDefaultOpts).then(
      (res) => {
        loadingNum--;
        if(loadingNum<=1){
        	//console.log("close")
          Indicator.close();
        }
        resolve(res)
      }
    ).catch(
      (res) => {
        switch(res.response.status){
          case 401:
            localStorage.removeItem('token');
            router.replace({name:'login_phoneLogin'});
            break;
        }
        reject(res);
        Indicator.close();
      }
    )

  });

  promise.setLoading = function(flag) {
    loading = flag;
  }
  return promise
};


export default fetch;
